<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/7/2
 * Time: 16:59
 */

namespace app\modules\controllers;


use app\models\Category;

class CategoryController extends CommonController
{
        public function actionList()
        {
            $this->layout = "layout1";
            $model = new Category();
            $cates = $model->getTreeList();
            return $this->render("cates", ['cates' => $cates]);
        }

        public function actionAdd()
        {
            $this->layout = "layout1";
            $model = new Category();
            $list = $model->getOptions();
            if (\Yii::$app->request->isPost) {
                $data = \Yii::$app->request->post();
                if ($model->add($data)) {
                    \Yii::$app->session->setFlash("info","添加成功");
                }
            }
            return $this->render("add",['list' => $list,'model' => $model]);
        }

        public function actionMod()
        {
           $this->layout = "layout1";
           $cateid = \Yii::$app->request->get("cateid");
           $model = Category::find()->where(['cateid' => $cateid])->one();
           if (\Yii::$app->request->isPost) {
               $data = \Yii::$app->request->post();
               if ($model->load($data) && $model->save()) {
                   \Yii::$app->session->setFlash("info","修改成功");
               }
           }
            $list = $model->getOptions();
            return $this->render('add', ['model' => $model, 'list' => $list]);
        }

        public function actionDel()
        {
            try {
                $cateid = \Yii::$app->request->get("catid");
                if (empty($cateid)) {
                    throw new \Exception("参数错误");
                }
                $child = Category::find()->where(['parentid' => $cateid])->exists();
                if ($child) {
                    throw new \Exception("该分类下有子类");
                }
                $res = Category::deleteAll(['cateid' => $cateid]);
                if (!$res) {
                    throw  new \Exception("删除失败");
                }
            } catch(\Exception $e){
                \Yii::$app->session->setFlash("info",$e->getMessage());
            }
            return $this->redirect(['category/list']);
        }
}